<!--订单详情-->
<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="order-page-container">
                
                <!-- 订单详情 -->
                <div class="idle-info-container" @click="toDetails(orderInfo.idleItem.id)">
                    
                    <!-- 商品图片 -->
                    <el-image
                            style="width: 150px; height: 150px;"
                            :src="$store.state.baseApi + orderInfo.idleItem.imgUrl"
                            fit="cover">
                    </el-image>
                    
                    <!-- 订单商品名称 -->
                    <!-- 比较现在userid和orderInfo.userId是否一样，一样则显示“买到的”，否则显示“卖出的” -->
                    <div class="idle-info-title">{{orderInfo.userId==userId?'买到的':'卖出的'}}：{{orderInfo.idleItem.idleName}}</div>
    
                    <!-- 订单价格 -->
                    <div class="idle-info-price">￥{{orderInfo.orderPrice}}</div>
                </div>
                
                <!-- 收货地址  信息和手机号-->
                <div class="address-container">
                    <div class="address-title">收货信息: {{addressInfo.consigneeName}} {{addressInfo.consigneePhone}}</div>
                    <div class="address-detials">{{addressInfo.detailAddress}}</div>
                </div>

                <!-- 订单信息 -->
                <div class="order-info-container">
                    <div class="order-info-title">订单信息（{{orderStatus[orderInfo.orderStatus]}}）：</div>
                    <div class="order-info-item">编号：{{orderInfo.orderNumber}}</div>
                    <div class="order-info-item">支付状态：{{orderInfo.paymentStatus===0?'未支付':'已支付'}}</div>
                    <div class="order-info-item">支付方式：{{orderInfo.paymentWay}}</div>
                    <div class="order-info-item">创建时间：{{orderInfo.createTime.substring(0, 10) + ' ' +orderInfo.createTime.substring(11, 19)}}</div>
                    <div class="order-info-item">支付时间：{{orderInfo.paymentTime?orderInfo.paymentTime.substring(0, 10) + ' ' +orderInfo.paymentTime.substring(11, 19):''}}</div>
                </div>

                <!-- 订单相关按钮  包含取消 支付 发货 确认收获 -->
                <div class="menu">
                    <!-- 订单状态orderStatus   0'待付款', 1'待发货', 2'待收货', 3'已完成', 4'已取消' -->
                    <!-- 客户端 付款 -->
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===0" type="danger" plain @click="changeOrderStatus(4,orderInfo)"> 取消订单</el-button>
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===0" type="primary" plain @click="changeOrderStatus(1,orderInfo)"> 立即支付</el-button>
                    <!-- 商家端 发货 -->
                    <el-button v-if="userId==orderInfo.idleItem.userId&&orderInfo.orderStatus===1" type="primary" plain @click="changeOrderStatus(2,orderInfo)"> 发货</el-button>
                    <!-- 客户端 确认收货 -->
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===2" type="primary" plain @click="changeOrderStatus(3,orderInfo)"> 确认收货</el-button>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'

    export default {
        name: "order",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                addressData: [],//地址列表
                orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消'],//订单状态 01234
                orderInfo: {//订单信息
                    createTime: "",
                    id: 0,
                    idleId: 0,
                    idleItem: {//商品信息
                        id: '',
                        idleName: '',
                        idleDetails: '',
                        pictureList: [],
                        idlePrice: 0,
                        idlePlace: '',
                        idleLabel: '',
                        idleStatus: -1,
                        userId: '',
                    },
                    orderNumber: "",
                    orderPrice: 0,
                    orderStatus: 0,
                    paymentStatus: 0,//支付状态 0未支付 1已支付
                    paymentTime: "",
                    paymentWay: "",
                    userId: 0
                },
                addressInfo: {//收货地址信息
                    id:'',
                    update:false,
                    consigneeName: '',//收货人
                    consigneePhone: '',//收货人电话
                    detailAddress: ''//详细地址
                },
                userId:'',
                money: 0,
            };
        },
        created() {
            this.userId = this.getCookie('shUserId');
            console.log('userId', this.userId, this.getCookie('shUserId'));
            let orderId = this.$route.query.id;
            console.log(orderId);
            this.$api.getOrder({ id: orderId }).then(res => {
                if (res.status_code === 1) {
                    if (res.data.idleItem) {
                        let imgList = JSON.parse(res.data.idleItem.pictureList);
                        if (imgList.length > 0) {
                            res.data.idleItem.imgUrl = imgList[0];
                        } else {
                            res.data.idleItem.imgUrl = '';
                        }
                    } else {
                        res.data.idleItem = {
                            idleName: '',
                            imgUrl: ''
                        }
                    }
                    // 获取用户资金信息
                    this.$api.getUserMoney({ userId: this.userId }).then(res => {
                        if (res.status_code === 1) {
                            this.money = res.data.money;
                        }
                    });
                    this.orderInfo = res.data;
                    this.$api.getOrderAddress({ orderId: this.orderInfo.id }).then(res => {
                        if (res.data) {
                            this.addressInfo = res.data;
                            this.addressInfo.update = true;
                        } else {
                            this.getAddressData();
                        }
                    });
                }
            });

            
        },

        methods: {
            getCookie(cname){//Cookie是存储在用户本地终端上的数据，记录用户信息。
                var name = cname + "=";
                var ca = document.cookie.split(';');//获取所有的 Cookie，并分割成一个数组
                for(var i=0; i<ca.length; i++)
                {
                    var c = ca[i].trim();//除去字符串两边的空格
                    if (c.indexOf(name)===0) return c.substring(name.length,c.length);//当前Cookie名称是要获取的名称，返回Cookie值
                }
                return "0";//如果没有cookie则返回0
            },
            toDetails(id) {//跳转到商品详情
                this.$router.replace({path: 'details', query: {id: id}});
            },
            getAddressData() { // 获取设置的地址列表
                this.$api.getAddress().then(res => {
                    if (res.status_code === 1) {
                        let data = res.data;
                        for (let i = 0; i < data.length; i++) { // 返回的地址信息拼接成详细地址
                            data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;
                        }
                        console.log(data);
                        this.addressData = data; // 拼接完的详细地址信息传给地址数据

                        // 获取默认地址并设置地址信息
                        for (let i = 0; i < data.length; i++) {
                            if (data[i].defaultFlag) {//如果是默认地址
                                this.addressInfo.consigneeName = data[i].consigneeName;
                                this.addressInfo.consigneePhone = data[i].consigneePhone;
                                this.addressInfo.detailAddress = data[i].detailAddressText;
                                break; // 已找到默认地址，跳出循环
                            }
                        }
                    }
                });
            },
            // 订单状态orderStatus   0'待付款', 1'付款--》待发货', 2'发货--》待收货', 3'已完成', 4'已取消'
            //支付状态paymentStatus=0 未支付，paymentStatus=1已支付

            //修改订单状态  接收两个参数：订单状态和订单信息
            changeOrderStatus(orderStatus, orderInfo) { 
                if (orderStatus === 1) { // 如果订单状态为1，表示需要支付  未支付--》支付
                    console.log('zhifu'); 
                    //确认对话框
                    this.$confirm('模拟支付宝支付，是否确认支付', '支付订单', {   
                        confirmButtonText: '支付',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => { 
                        // 点击确认按钮
                        if (this.money < orderInfo.orderPrice) {
                            this.$message({
                                message: '余额不足，无法支付！',
                                type: 'error'
                            });
                            return; // 阻止支付操作
                        }
                        this.$api.updateOrder({  //传递给这个api的四个参数，要求后端更新订单参数
                            id: orderInfo.id,
                            orderStatus: orderStatus,
                            paymentStatus: 1,
                            paymentWay: '支付宝',
                        }).then(res => { // API响应后的操作
                            if (res.status_code === 1) { // 如果服务器返回的状态码为1，表示操作成功
                                this.$message({
                                    message: '支付成功！',
                                    type: 'success'
                                });
                                // 更新订单信息
                                this.orderInfo.orderStatus = orderStatus;
                                this.orderInfo.paymentStatus = 1; // 已支付
                                this.orderInfo.paymentWay = '支付宝';
                                this.orderInfo.paymentTime = res.data.paymentTime; // 支付时间
                                // 更新用户资金信息
                                this.money -= orderInfo.orderPrice;

                                // 确保在订单成功更新后再更新用户资金信息
                                this.$api.updateUserMoney({
                                    userId: this.userId,
                                    money: this.money
                                }).then(res => {
                                    if (res.status_code === 1) {
                                        this.$message({
                                            message: '资金更新成功！',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: '资金更新失败，请联系客服！',
                                            type: 'error'
                                        });
                                    }
                                }).catch(() => {
                                    this.$message({
                                        message: '资金更新请求失败，请稍后再试！',
                                        type: 'error'
                                    });
                                });
                            }
                        }).catch(() => {
                            this.$message({
                                message: '订单更新失败，请稍后再试！',
                                type: 'error'
                            });
                        });
                    }).catch(() => { // 点击取消按钮
                        // 这里处理取消支付的逻辑
                    });
                } else { // 如果订单状态不为1 比如  商家端：发货--》待收货 ，客户端 待收货--》收货 
                    // 直接调用API更新订单状态
                    this.$api.updateOrder({
                        id: orderInfo.id,
                        orderStatus: orderStatus,
                    }).then(res => {
                        if (res.status_code === 1) { // 如果服务器返回的状态码为1，表示操作成功
                            // 显示一个成功的消息
                            this.$message({
                                message: '操作成功！',
                                type: 'success'
                            });
                            // 更新订单状态
                            this.orderInfo.orderStatus = orderStatus;
                        }
                    }).catch(() => {
                        this.$message({
                            message: '操作失败，请稍后再试！',
                            type: 'error'
                        });
                    });
                }
            },
        }
    }
</script>

<style scoped>
    .order-page-container {
        min-height: 85vh;
    }

    .idle-info-container {
        width: 100%;
        display: flex;
        border-bottom: 20px solid #f6f6f6;
        padding: 20px;
        cursor: pointer;
    }

    .idle-info-title {
        font-size: 18px;
        font-weight: 600;
        max-width: 750px;
        margin-left: 10px;
    }

    .idle-info-price {
        font-size: 18px;
        color: red;
        margin-left: 10px;
    }

    .address-container {
        min-height: 60px;
        padding: 20px;
        border-bottom: 20px solid #f6f6f6;

    }

    .address-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 10px;
    }

    .address-detials {
        font-size: 16px;
        color: #444444;
    }

    .order-info-container {
        padding: 20px;
    }

    .order-info-item {
        margin: 10px 0;
        font-size: 14px;
        color: #444444;
    }

    .menu {
        margin-left: 20px;
    }
</style>